import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import store from '../store'

// 懒加载组件
const Home = () => import('../views/Home.vue')
const RoutePlan = () => import('../views/RoutePlan.vue')
const Attractions = () => import('../views/Attractions.vue')
const AttractionDetail = () => import('../views/AttractionDetail.vue')
const Budget = () => import('../views/Budget.vue')
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Itineraries = () => import('../views/Itineraries.vue')
const Social = () => import('../views/Social.vue')
const AdminDashboard = () => import('../views/AdminDashboard.vue')
const AdminAttractions = () => import('../views/AdminAttractions.vue')
const RouteShare = () => import('../views/RouteShare.vue')
const Favorites = () => import('../views/Favorites.vue')
const AttractionsMap = () => import('../views/AttractionsMap.vue')
const RecommendedRoutes = () => import('../views/RecommendedRoutes.vue')
const AttractionRankings = () => import('../views/AttractionRankings.vue')
const PermissionsInfo = () => import('../views/PermissionsInfo.vue')
const AdminSettings = () => import('../views/AdminSettings.vue')
const AdminLogs = () => import('../views/AdminLogs.vue')
const UserProfile = () => import('../views/UserProfile.vue')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/route-plan',
    name: 'RoutePlan',
    component: RoutePlan,
    meta: { requiresAuth: true }
  },
  {
    path: '/attractions',
    name: 'Attractions',
    component: Attractions
  },
  {
    path: '/attractions/:id',
    name: 'AttractionDetail',
    component: AttractionDetail
  },
  {
    path: '/attractions/map',
    name: 'AttractionsMap',
    component: AttractionsMap
  },
  {
    path: '/attractions/rankings',
    name: 'AttractionRankings',
    component: AttractionRankings
  },
  {
    path: '/routes/recommended',
    name: 'RecommendedRoutes',
    component: RecommendedRoutes
  },
  {
    path: '/budget',
    name: 'Budget',
    component: Budget
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/itineraries',
    name: 'Itineraries',
    component: Itineraries,
    meta: { requiresAuth: true }
  },
  {
    path: '/social',
    name: 'Social',
    component: Social,
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/attractions',
    name: 'AdminAttractions',
    component: AdminAttractions,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/users',
    name: 'AdminUsers',
    component: () => import('../views/AdminUsers.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/posts',
    name: 'AdminPosts',
    component: () => import('../views/AdminPosts.vue'),
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/settings',
    name: 'AdminSettings',
    component: AdminSettings,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/admin/logs',
    name: 'AdminLogs',
    component: AdminLogs,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/route-share/:code',
    name: 'RouteShare',
    component: RouteShare
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: Favorites,
    meta: { requiresAuth: true }
  },
  {
    path: '/permissions',
    name: 'PermissionsInfo',
    component: PermissionsInfo
  },
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: UserProfile,
    meta: { requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated
  const isAdmin = store.getters.isAdmin
  
  // 如果用户已登录，尝试刷新用户信息（检查权限变更）
  if (isAuthenticated && store.state.token) {
    try {
      // 如果用户信息不存在，尝试获取
      if (!store.state.user) {
        await store.dispatch('fetchUserInfo')
      }
    } catch (error) {
      // Token可能已过期，清除登录状态
      if (error.response?.status === 401) {
        store.dispatch('logout')
        ElMessage.warning('登录已过期，请重新登录')
        next({ name: 'Login', query: { redirect: to.fullPath } })
        return
      }
    }
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !isAuthenticated) {
    ElMessage.info('请先登录')
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }
  
  // 管理员访问普通用户功能或公共浏览功能时，跳转到管理后台
  if (isAuthenticated && isAdmin) {
    // 如果访问管理员功能，直接允许通过
    if (to.path.startsWith('/admin')) {
      next()
      return
    }
    
    // 普通用户专用功能路径
    const userOnlyPaths = ['/dashboard', '/itineraries', '/social', '/favorites', '/route-plan']
    // 公共浏览功能路径（管理员不应该在侧边栏看到，但可以通过URL访问，需要重定向）
    const publicBrowsePaths = ['/', '/attractions', '/routes/recommended']
    
    // 允许管理员访问的公共页面（用于管理目的）
    const adminAllowedPaths = ['/route-share', '/attractions/'] // 分享路线、景点详情（用于管理）
    
    // 检查是否是允许管理员访问的路径
    const isAdminAllowedPath = adminAllowedPaths.some(path => {
      if (path.endsWith('/')) {
        // 对于 /attractions/，匹配 /attractions/:id 格式
        return to.path.startsWith(path) && to.path !== '/attractions' && to.path !== '/attractions/map' && to.path !== '/attractions/rankings'
      }
      return to.path.startsWith(path)
    })
    
    // 如果访问普通用户功能，重定向到管理后台
    if (userOnlyPaths.some(path => to.path.startsWith(path))) {
      ElMessage.info('管理员请使用管理后台进行系统管理')
      next({ name: 'AdminDashboard' })
      return
    }
    
    // 如果访问公共浏览功能（首页、景点探索、热门路线），也重定向到管理后台
    // 但允许访问景点详情和分享路线（用于管理目的）
    if (publicBrowsePaths.some(path => to.path === path || to.path.startsWith(path)) && !isAdminAllowedPath) {
      ElMessage.info('管理员请使用管理后台，如需测试浏览功能请使用普通用户账号')
      next({ name: 'AdminDashboard' })
      return
    }
  }
  
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin || to.path.startsWith('/admin')) {
    if (!isAuthenticated) {
      ElMessage.info('请先登录')
      next({ name: 'Login', query: { redirect: to.fullPath } })
      return
    }
    
    if (!isAdmin) {
      ElMessage.error('您没有管理员权限')
      next({ name: 'Dashboard' })
      return
    }
  }
  
  // 已登录用户访问登录/注册页，根据角色跳转
  if ((to.name === 'Login' || to.name === 'Register') && isAuthenticated) {
    if (isAdmin) {
      next({ name: 'AdminDashboard' })
    } else {
      next({ name: 'Dashboard' })
    }
    return
  }
  
  // 所有检查通过，允许导航
  next()
})

export default router

